<!--
  * 新增进件
-->
<template>
  <a-modal title="新增进件" :width="1000" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" :disabled="props.formType == 'view'">
      <a-row :gutter="16">
        <a-col :span="24">
          <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">选择商户</group-title>
        </a-col>
        <a-col :span="24">
          <a-form-item label="商户名称" name="merchantId">
            <CustomSelect
              v-model:value="formData.merchantId"
              :placeholder="'请选择商户名称'"
              :api="merchantApi.page"
              queryParamKey="companyNameLeftLike"
              @change="(...value) => changeCompanyName(value)"
              labelField="companyName,no"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">选择通道</group-title>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="是否直连" name="directFlag">
            <a-radio-group v-model:value="formData.directFlag" :options="YES_OR_NO" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label=" 通道类型" name="channelType">
            <a-select v-model:value="formData.channelType" :options="ZZB_CHANNEL_TYPE" placeholder="请选择" @change="handleChannelTypeChange" />
          </a-form-item>
        </a-col> -->
        <a-col :span="24">
          <a-form-item label="通道名称" class="smart-query-form-item" name="channelId">
            <CustomSelect
              v-model:value="formData.channelId"
              :placeholder="'请选择'"
              :api="channelApi.queryPage"
              @change="changeChannel"
              :responseAdapter="resFun"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">选择产品</group-title>
        </a-col>
        <a-col :span="24">
          <a-form-item label="产品名称" class="smart-query-form-item" name="productId">
            <CustomSelect
              v-model:value="formData.productId"
              :placeholder="'请选择产品名称'"
              @change="(...data) => changeProductName(data)"
              :queryParams="{ channelType: formData.channelType, status: 1 }"
              :api="productPage"
              label-field="productName"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <a-space v-if="props.formType != 'view'">
        <a-button @click="onClose">取消</a-button>
        <!-- <a-button @click="onSubmit">保存</a-button> -->
        <a-button type="primary" @click="showForm">填写进件资料</a-button>
      </a-space>
    </template>
  </a-modal>
  <AlipayForm v-model:open="alipayFormOptions.open" formType="add" :rowData="alipayFormOptions.rowData" :params="{ apiType }" />
  <WeChatForm v-model:open="weChatFormOptions.open" formType="add" :rowData="weChatFormOptions.rowData" :params="{ apiType }" />
  <LakalaForm v-model:open="lakalaFormOptions.open" formType="add" :rowData="lakalaFormOptions.rowData" />
</template>
<script setup>
  import { ref, nextTick, computed, watch } from 'vue'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { merchantApi } from '/@/api/business/b-agent/merchant/merchant-api'
  import { registApi } from '/@/api/business/b-agent/regist/index.js'
  import { channelApi } from '/@/api/business/b-agent/channel/channel-api'
  import { productPage } from '/@/api/business/b-agent/product'
  import { smartSentry } from '/@/lib/smart-sentry'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import AlipayForm from '/@/components/business/comment/regist/alipayForm.vue'
  import WeChatForm from '/@/components/business/comment/regist/weChatForm.vue'
  import LakalaForm from '/@/components/business/comment/regist/lakalaForm.vue'
  import {
    ZZB_CHANNEL_TYPE, // 是否
  } from '/@/constants/dict'
  import { selectDictLabel } from '/@/utils/common'
  import { isEmpty } from 'lodash'

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['ok', 'update:open'])
  const visibleFlag = computed({ get: () => props.open, set: (val) => emits('update:open', val) })

  // ------------------------ 显示与隐藏 ------------------------
  function onClose() {
    Object.assign(formData.value, formDefault)
    visibleFlag.value = false
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  // ------------------------ 获取表单数据 ------------------------
  // async function getFormData(data) {
  //   SmartLoading.show()
  //   try {
  //     let res = await appAuthFindId(data)
  //     formData.value = { ...res.data, authAppArr: strToArr(res.data.authApp) }
  //   } catch (err) {
  //     smartSentry.captureError(err)
  //   } finally {
  //     SmartLoading.hide()
  //   }
  // }
  // 切换通道
  const changeChannel = (...data) => {
    if (isEmpty(data[1][0])) return
    formData.value.directFlag = data[1][0].directFlag ? 1 : 0
    formData.value.channelType = data[1][0].channelType
    formData.value.productId = undefined
  }
  // 通道数据整理
  const resFun = (res) => {
    res.data = res.data.map((item) => {
      return {
        ...item,
        name: `${item.channelName}-${selectDictLabel(ZZB_CHANNEL_TYPE, item.channelType)}`,
      }
    })
    return res
  }
  // 切换通道类型
  const handleChannelTypeChange = (data) => {
    formData.value.productId = undefined
  }
  const apiType = ref(0)
  //选择产品
  function changeProductName(data) {
    apiType.value = data[1][0].apiType
    formData.value.productName = data[1][0].productName
    console.log('选择产品===>', data)
  }
  /* 切换商家 */
  function changeCompanyName(data) {
    if (!data[1][0]) {
      formData.value.merchantId = undefined
      return
    }
    // console.log('选择商家===>', data[1][0])
    formData.value.merchantId = data[1][0].id
    formData.value.agentId = data[1][0].pAgentId
  }
  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    merchantId: undefined,
    directFlag: undefined,
    channelType: undefined,
    channelId: undefined,
    productId: undefined,
    productName: undefined,
    id: undefined,
  }

  let formData = ref({ ...formDefault })

  const rules = {
    merchantId: [{ required: true, message: '商家 必填' }],
    directFlag: [{ required: true, message: '是否直连 必填' }],
    channelType: [{ required: true, message: '通道类型 必填' }],
    channelId: [{ required: true, message: '通道名称 必填' }],
    productId: [{ required: true, message: '产品名称 必填' }],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      let res = await save()
      return res
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show()
    try {
      let data = { ...formData.value }
      let res = await registApi.insertMerchantsProduct(data)
      message.success('操作成功')
      emits('ok')
      return res
    } catch (err) {
      // message.error(JSON.stringify(err))
      console.log(JSON.stringify(err))
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  // 支付宝详情
  const alipayFormOptions = ref({
    open: false,
    rowData: {},
  })
  // 微信详情
  const weChatFormOptions = ref({
    open: false,
    rowData: {},
  })
  // 拉卡拉详情
  const lakalaFormOptions = ref({
    open: false,
    rowData: {},
  })
  async function showForm(row) {
    // console.log('formData.value===>', formData.value)

    let res = await onSubmit()
    console.log('res===>', res)
    if (res?.code == 200) {
      let data = { ...formData.value, id: res.data.id, apiType: apiType.value }
      console.log('data===>', data)
      if (data.channelType == 1) {
        alipayFormOptions.value = {
          open: true,
          rowData: data,
        }
      } else if (data.channelType == 2) {
        weChatFormOptions.value = {
          open: true,
          rowData: data,
        }
      } else if (data.channelType == 5) {
        lakalaFormOptions.value = {
          open: true,
          rowData: data,
        }
      }
      onClose()
    }
  }

  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      console.log('formData.value==>', formData.value)

      if (props.formType == 'add' && props.rowData?.applicationId) {
        formData.value.applicationId = props.rowData.applicationId
      }
      if (props.open && props.rowData && props.formType != 'add') {
        // getFormData(val[0])
      }
    },
    { immediate: true },
  )
</script>
